<?php 

namespace Libs\aws;

use Aws\Ses\SesClient;
use Libs\aws\Message;
use \Exception;
/**
 * class Send Email from SES Amazone
 * 
 * @access  public
 * @author TinNT1 (tinnt1@vitalify.asia)
 * @copyright Copyright@2014 Vitaliify Asia. All Rights Reserved.
 * create date : 20/3/2014
 */
class AWSSendEmail {
	private $_accessKey = '';
	private $_secretKey = '';
	private $_region 	= ''; 
	
	/**
	 * init AWSSendMail client 
	 *
	 * @author TinNT1 (tinnt1@vitalify.asia)
	 * create date : 20/3/2014
	 */
	public function __construct($sAccessKey = '', $sSecretKey = '', $sRegion = '') {
		$this->_accessKey = $sAccessKey;
		$this->_secretKey = $sSecretKey;
		$this->_region = $sRegion;
	}
	
	/**
	 * set access key
	 * 
	 * @author TinNT1 (tinnt1@vitalify.asia)
	 * @param 	string	$sAccessKey		access key from AWS
	 */
	public function setAccessKey($sAccessKey){
		$this->_accessKey = $sAccessKey;
	}
	
	/**
	 * set secret key
	 * 
	 * @author TinNT1 (tinnt1@vitalify.asia)
	 * @param 	string	$sSecretKey		secret key from AWS
	 */
	public function setSecretKey($sSecretKey){
		$this->_secretKey = $sSecretKey;
	}
	
	/**
	 * set region key
	 * 
	 * @author TinNT1 (tinnt1@vitalify.asia)
	 * @param 	string	$sRegion		region from AWS
	 */
	public function setRegion($sRegion){
		$this->_region = $sRegion;
	}
	
	/**
	 * send email static
	 * 
	 * @author TinNT1 (tinnt1@vitalify.asia)	 
	 * @param	Message	$m			Message
	 * @return 	array 	$result		Response from AWS
	 * create date : 20/3/2014
	 */
	public function sendEmail(Message $m){
		$result = array();
		$client = SesClient::factory(array(
		    'key'    => $this->_accessKey,//YOUR_AWS_ACCESS_KEY_ID
		    'secret' => $this->_secretKey,
		    'region' => $this->_region
		));
		try {
			if($m->isMessageRaw()) {						
				$response = $client->SendRawEmail($m->getRawMessagePackage());				
			} else {				
				$response = $client->SendEmail($m->getMessagePackage());				
			}
			$response = $response->toArray();
			$result['responseStatus'] = 1;
			$result['responseData'] = array('MessageId' => $response['MessageId'],
											'RequestId' => $response['ResponseMetadata']['RequestId']);	
		} catch (\Exception $ex){
			$result['responseStatus'] = 0;
			// $result['error'] = array(	'StatusCode' 	=> $ex->getStatusCode(),
										// 'ExceptionCode' => $ex->getExceptionCode(),
										// 'Message' 		=> "" . $ex->getResponse()->xml()->Error->Message,
										// 'RequestId' 	=> $ex->getRequestId());
			$result['error'] = array('Message' => $ex -> getMessage());
		}
		return $result;		
	}	
	
}
